package com.example.diethealthsystem.controller;

import com.example.diethealthsystem.entity.User;
import com.example.diethealthsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserRestController {

    @Autowired
    private UserRepository userRepository;

    // 查询所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 查询单个用户
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        Optional<User> user = userRepository.findById(id);
        return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 新增用户
    @PostMapping
    public ResponseEntity<?> addUser(@RequestBody User user) {
        // 用户名和邮箱唯一性校验
        if (userRepository.findByUsername(user.getUsername()).isPresent() ||
            userRepository.findByEmail(user.getEmail()).isPresent()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名或邮箱已存在");
        }
        User saved = userRepository.save(user);
        return ResponseEntity.ok(saved);
    }

    // 修改用户
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        Optional<User> oldUserOpt = userRepository.findById(id);
        if (oldUserOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        User oldUser = oldUserOpt.get();
        // 更新字段
        oldUser.setUsername(user.getUsername());
        oldUser.setPassword(user.getPassword());
        oldUser.setEmail(user.getEmail());
        oldUser.setDisplayName(user.getDisplayName());
        oldUser.setRole(user.getRole());
        oldUser.setGender(user.getGender());
        oldUser.setAge(user.getAge());
        oldUser.setHeight(user.getHeight());
        oldUser.setWeight(user.getWeight());
        oldUser.setPhone(user.getPhone());
        oldUser.setBanned(user.getBanned());
        oldUser.setAvatarUrl(user.getAvatarUrl());
        // 其它字段可根据需要补充
        userRepository.save(oldUser);
        return ResponseEntity.ok(oldUser);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        if (!userRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        userRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
} 